package com.xiaguliuxiang.sql.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

/**
 * SqlRunnerController
 *
 * @author xiaguliuxiang@foxmail.com
 * @date 2021/05/01
 */
@RestController
@RequestMapping("/sql")
public class SqlRunnerController {

    private static final Logger log = LoggerFactory.getLogger(SqlRunnerController.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Query
    @PostMapping("/query")
    public Object query(@RequestParam("sql") String sql) {
        log.info("run query:{}", sql);
        return entityManager.createNativeQuery(sql).getResultList();
    }

    @Modifying
    @PostMapping("/modify")
    @Transactional(rollbackOn = {Exception.class})
    public Integer modify(@RequestParam("sql") String sql) {
        log.info("run modify:{}", sql);
        int executeUpdate = entityManager.createNativeQuery(sql).executeUpdate();
        log.info("run modify result:{}", executeUpdate);
        return executeUpdate;
    }
}
